package yunjiao.javatutorials.guava.concurrent.api;

import com.google.common.util.concurrent.RateLimiter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

/**
 *  实现拦截器
 *
 * @author yangyunjiao
 */
@Component
@RequiredArgsConstructor
public class RateLimitInterceptor implements HandlerInterceptor {
    private final RateLimiter globalRateLimiter;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 尝试获取令牌，最多等待 300 毫秒
        boolean acquired = globalRateLimiter.tryAcquire(1, 300, TimeUnit.MILLISECONDS);
        if (!acquired) {
            response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            response.getWriter().write("Too Many Requests (QPS Limit: " + globalRateLimiter.getRate() + ")");
            return false;
        }
        return true;
    }
}
